// 用户个人中心页面脚本

// 用户状态管理
const checkLoginStatus = () => {
  try {
    let userStr = localStorage.getItem('user');
    let isLoggedIn = localStorage.getItem('isLoggedIn');
    
    if (!userStr || isLoggedIn !== 'true') {
      userStr = sessionStorage.getItem('user');
      isLoggedIn = sessionStorage.getItem('isLoggedIn');
    }
    
    return userStr && isLoggedIn === 'true';
  } catch (error) {
    // console.error('Failed to check login status:', error);
    return false;
  }
};

const getCurrentUser = () => {
  try {
    let userStr = localStorage.getItem('user');
    
    if (!userStr) {
      userStr = sessionStorage.getItem('user');
    }
    
    return userStr ? JSON.parse(userStr) : null;
  } catch (error) {
    // console.error('Failed to parse user data:', error);
    return null;
  }
};

const updateNavbarUserDisplay = () => {
  const navLogin = document.getElementById('nav-login');
  const userDropdown = document.getElementById('user-dropdown');
  const navUsername = document.getElementById('nav-username');
  const navUserAvatar = document.getElementById('nav-user-avatar');
  
  if (checkLoginStatus()) {
    const user = getCurrentUser();
    if (user) {
      navLogin.style.display = 'none';
      userDropdown.style.display = 'block';
      navUsername.textContent = user.nickname || user.account;
      
      // 设置导航栏头像
      if (user.avatar && user.avatar !== 'img/default-avatar.png') {
        // 如果是上传的头像，添加时间戳防止缓存
        const avatarUrl = user.avatar.startsWith('img/') ? `../${user.avatar}` : user.avatar;
        const finalAvatarUrl = `${avatarUrl}?t=${Date.now()}`;
        
        navUserAvatar.src = finalAvatarUrl;
        
        // 添加错误处理
        navUserAvatar.onerror = () => {
          console.warn('⚠️ [User页面] 导航栏头像加载失败，使用默认头像:', avatarUrl);
          navUserAvatar.src = '../img/default-avatar.png';
          navUserAvatar.onerror = null;
        };
      } else {
          navUserAvatar.src = '../img/default-avatar.png';
        }
    }
  } else {
    navLogin.style.display = 'block';
    userDropdown.style.display = 'none';
  }
};

const logout = () => {
  localStorage.removeItem('user');
  localStorage.removeItem('isLoggedIn');
  localStorage.removeItem('rememberLogin');
  
  sessionStorage.removeItem('user');
  sessionStorage.removeItem('isLoggedIn');
  
  window.location.href = 'account.html';
};

// 页面初始化
document.addEventListener('DOMContentLoaded', () => {
  // 检查登录状态
  if (!checkLoginStatus()) {
    window.location.href = 'account.html';
    return;
  }
  
  updateNavbarUserDisplay();
  loadUserData();
  setupEventListeners();
});

// 加载用户数据
const loadUserData = () => {
  const user = getCurrentUser();
  if (!user) return;
  
  document.getElementById('user-account').value = user.account || '';
  document.getElementById('user-nickname').value = user.nickname || '';
  
  // 智能填充手机号和邮箱
  // 如果用户数据中已有手机号/邮箱，优先使用
  // 否则根据注册账号类型自动填充
  let phoneValue = user.phone || '';
  let emailValue = user.email || '';
  
  // 如果手机号字段为空，检查注册账号是否为手机号
  if (!phoneValue && user.account) {
    const phoneRegex = /^1[3-9]\d{9}$/; // 中国手机号正则
    if (phoneRegex.test(user.account)) {
      phoneValue = user.account;
    }
  }
  
  // 如果邮箱字段为空，检查注册账号是否为邮箱
  if (!emailValue && user.account) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // 邮箱正则
    if (emailRegex.test(user.account)) {
      emailValue = user.account;
    }
  }
  
  document.getElementById('user-phone').value = phoneValue;
  document.getElementById('user-email').value = emailValue;
  document.getElementById('user-bio').value = user.bio || '';
  
  // 设置性别
  if (user.gender) {
    // 移除所有按钮的active类
    document.querySelectorAll('.gender-btn').forEach(btn => btn.classList.remove('active'));
    // 为对应的按钮添加active类
    const genderBtn = document.querySelector(`[data-value="${user.gender}"]`);
    if (genderBtn) {
      genderBtn.classList.add('active');
      document.getElementById('gender-hidden').value = user.gender;
    }
  }
  
  // 设置头像
  const userAvatar = document.getElementById('user-avatar');
  if (user.avatar && user.avatar !== 'img/default-avatar.png') {
    // 如果是上传的头像，添加时间戳防止缓存
    const avatarUrl = user.avatar.startsWith('img/') ? `../${user.avatar}` : user.avatar;
    const finalAvatarUrl = `${avatarUrl}?t=${Date.now()}`;
    
    userAvatar.src = finalAvatarUrl;
    
    // 添加错误处理
    userAvatar.onerror = () => {
      console.warn('⚠️ [User页面] 个人中心头像加载失败，使用默认头像:', avatarUrl);
      userAvatar.src = '../img/default-avatar.png';
      userAvatar.onerror = null;
    };
  } else {
      userAvatar.src = '../img/default-avatar.png';
    }
  
  // 更新字符计数
  updateCharCount();
  
  // 保存初始数据用于比较
  window.initialFormData = getFormData();
};

// 获取表单数据
const getFormData = () => {
  return {
    nickname: document.getElementById('user-nickname').value,
    gender: document.getElementById('gender-hidden').value,
    phone: document.getElementById('user-phone').value,
    email: document.getElementById('user-email').value,
    bio: document.getElementById('user-bio').value
  };
};

// 检查表单是否有变化
const checkFormChanges = () => {
  if (!window.initialFormData) return false;
  
  const currentData = getFormData();
  return JSON.stringify(currentData) !== JSON.stringify(window.initialFormData);
};

// 更新保存按钮状态
const updateSaveButton = () => {
  const saveBtn = document.getElementById('save-btn');
  saveBtn.disabled = !checkFormChanges();
};

// 更新字符计数
const updateCharCount = () => {
  const bio = document.getElementById('user-bio');
  const count = document.getElementById('bio-count');
  count.textContent = bio.value.length;
};

// 设置事件监听器
const setupEventListeners = () => {
  // 登出按钮
  document.getElementById('logout-btn').addEventListener('click', logout);
  
  // 性别按钮点击事件
  document.querySelectorAll('.gender-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      // 移除所有按钮的active类
      document.querySelectorAll('.gender-btn').forEach(b => b.classList.remove('active'));
      // 为当前按钮添加active类
      btn.classList.add('active');
      // 更新隐藏输入框的值
      document.getElementById('gender-hidden').value = btn.dataset.value;
      // 触发保存按钮状态更新
      updateSaveButton();
    });
  });
  
  // 表单变化监听
  const formInputs = document.querySelectorAll('#user-form input, #user-form textarea');
  formInputs.forEach(input => {
    input.addEventListener('input', () => {
      updateSaveButton();
      if (input.id === 'user-bio') {
        updateCharCount();
      }
    });
  });
  
  // 表单提交
  document.getElementById('user-form').addEventListener('submit', handleFormSubmit);
  
  // 头像上传按钮
  document.getElementById('avatar-upload-btn').addEventListener('click', showAvatarUploadDialog);
  
  // 头像图片点击事件
  document.getElementById('user-avatar').addEventListener('click', showAvatarUploadDialog);
  
  // 为头像图片添加鼠标悬停效果，提示可点击
  const avatarImg = document.getElementById('user-avatar');
  avatarImg.style.cursor = 'pointer';
  avatarImg.title = '点击修改头像';
};

// 处理表单提交
const handleFormSubmit = async (e) => {
  e.preventDefault();
  
  const saveBtn = document.getElementById('save-btn');
  const originalText = saveBtn.textContent;
  
  try {
    saveBtn.disabled = true;
    saveBtn.textContent = '保存中...';
    
    const formData = getFormData();
    const user = getCurrentUser();
    
    if (!user || !user.id) {
      throw new Error('用户信息无效');
    }
    
    // 调用API更新用户信息到数据库
    const response = await ApiClient.updateUserInfo(user.id, formData);
    
    if (response.success) {
      // 使用服务器返回的完整用户数据
      const updatedUser = response.user;
      
      // 保存到存储
      const storage = localStorage.getItem('rememberLogin') === 'true' ? localStorage : sessionStorage;
      storage.setItem('user', JSON.stringify(updatedUser));
      
      // 更新初始数据
      window.initialFormData = getFormData();
      
      // 更新导航栏显示
      updateNavbarUserDisplay();
      
      showConfirmDialog('保存成功', '个人资料修改成功！');
    } else {
      throw new Error(response.message || '保存失败');
    }
    
  } catch (error) {
    // console.error('保存失败:', error);
    showConfirmDialog('保存失败', error.message || '请稍后重试');
  } finally {
    saveBtn.disabled = false;
    saveBtn.textContent = originalText;
    updateSaveButton();
  }
};

// 显示头像上传对话框
const showAvatarUploadDialog = () => {
  let selectedFile = null; // 存储选中的文件
  
  const dialogContent = `
    <div class="avatar-upload-dialog">
      <div class="upload-area" id="upload-area">
        <div class="upload-icon">📷</div>
        <div class="upload-text">拖拽图片到此处或点击选择文件<br><small>支持 JPG, PNG, GIF, WEBP 格式，最大2MB</small></div>
        <button type="button" class="upload-btn" id="select-file-btn">选择文件</button>
        <input type="file" id="file-input" accept="image/jpeg,image/jpg,image/png,image/gif,image/webp" style="display: none;">
      </div>
      
      <div class="preview-area" id="preview-area">
        <img id="preview-image" class="preview-image" alt="预览">
        <div class="crop-info">预览图片</div>
      </div>
      
      <div class="upload-progress" id="upload-progress" style="display: none;">
        <div class="progress-bar">
          <div class="progress-fill" id="progress-fill"></div>
        </div>
        <div class="progress-text" id="progress-text">上传中...</div>
      </div>
    </div>
  `;
  
  showActionDialog(
    '修改头像',
    dialogContent,
    {
      actionText: '确认',
      onAction: async () => {
        // console.log('🎯 确认按钮被点击！');
        
        if (!selectedFile) {
          showConfirmDialog('提示', '请先选择要上传的图片');
          return;
        }
        
        const user = getCurrentUser();
        // console.log('👤 当前用户信息:', user);
        
        if (!user || !user.id) {
          // console.error('❌ 用户信息无效:', user);
          showConfirmDialog('保存失败', '用户信息无效，请重新登录');
          return;
        }
        
        try {
          // console.log('🔄 开始上传头像...', {
           //   fileName: selectedFile.name,
           //   fileSize: selectedFile.size,
           //   fileType: selectedFile.type,
           //   userId: user.id
           // });
          
          // 显示上传进度
          const uploadProgress = document.getElementById('upload-progress');
          const progressFill = document.getElementById('progress-fill');
          const progressText = document.getElementById('progress-text');
          
          uploadProgress.style.display = 'block';
          progressFill.style.width = '0%';
          progressText.textContent = '准备上传...';
          
          // 创建FormData
          const formData = new FormData();
          formData.append('avatar', selectedFile);
          
          // 调用新的文件上传API
          // console.log('🔥 准备调用uploadAvatarFile函数');
          const response = await uploadAvatarFile(user.id, formData, (progress) => {
            // console.log('📊 上传进度:', progress + '%');
            progressFill.style.width = progress + '%';
            progressText.textContent = `上传中... ${progress}%`;
          });
          // console.log('🎯 uploadAvatarFile函数调用完成');
          
          // console.log('📡 API响应:', response);
          
          if (response && response.success) {
            progressText.textContent = '上传成功！';
            
            // 更新页面头像显示
            const userAvatar = document.getElementById('user-avatar');
            const navUserAvatar = document.getElementById('nav-user-avatar');
            
            const avatarUrl = `/${response.avatarPath}?t=${Date.now()}`; // 添加时间戳防止缓存
            
            if (userAvatar) userAvatar.src = avatarUrl;
            if (navUserAvatar) navUserAvatar.src = avatarUrl;
            
            // 更新本地存储
            const updatedUser = {
              ...user,
              avatar: response.avatarPath,
              lastUpdated: new Date().toISOString()
            };
            
            const storage = localStorage.getItem('rememberLogin') === 'true' ? localStorage : sessionStorage;
            storage.setItem('user', JSON.stringify(updatedUser));
            
            // 更新导航栏显示
            updateNavbarUserDisplay();
            
            // console.log('✅ 头像更新成功');
            showConfirmDialog('上传成功', '头像已更新并同步到服务器');
          } else {
            throw new Error(response?.error || '服务器响应异常');
          }
        } catch (error) {
          // console.error('❌ 头像保存失败 - 完整错误信息:', {
           //   message: error.message,
           //   stack: error.stack,
           //   name: error.name,
           //   error: error
           // });
          
          // 提供详细的错误信息
          let errorMessage = '头像保存失败';
          if (error.message.includes('Failed to fetch')) {
            errorMessage = '网络连接失败，请检查网络后重试';
          } else if (error.message.includes('文件大小超过')) {
            errorMessage = '图片文件过大，请选择小于2MB的图片';
          } else if (error.message.includes('不支持的文件格式')) {
            errorMessage = '不支持的文件格式，请选择 JPG, PNG, GIF 或 WEBP 格式';
          } else {
            errorMessage = `保存失败：${error.message}`;
          }
          
          // console.error('🚨 将显示给用户的错误信息:', errorMessage);
          showConfirmDialog('保存失败', errorMessage);
        }
      }
    }
  );
  
  // 设置文件上传事件
  setTimeout(() => {
    const fileInput = document.getElementById('file-input');
    const selectBtn = document.getElementById('select-file-btn');
    const uploadArea = document.getElementById('upload-area');
    const previewArea = document.getElementById('preview-area');
    const previewImage = document.getElementById('preview-image');
    
    selectBtn.addEventListener('click', () => fileInput.click());
    
    fileInput.addEventListener('change', (e) => {
      const file = e.target.files[0];
      if (file) {
        selectedFile = file; // 保存选中的文件
        handleFileUpload(file, uploadArea, previewArea, previewImage);
      }
    });
    
    // 拖拽上传
    uploadArea.addEventListener('dragover', (e) => {
      e.preventDefault();
      uploadArea.classList.add('dragover');
    });
    
    uploadArea.addEventListener('dragleave', () => {
      uploadArea.classList.remove('dragover');
    });
    
    uploadArea.addEventListener('drop', (e) => {
      e.preventDefault();
      uploadArea.classList.remove('dragover');
      
      const file = e.dataTransfer.files[0];
      if (file && file.type.startsWith('image/')) {
        selectedFile = file; // 保存选中的文件
        handleFileUpload(file, uploadArea, previewArea, previewImage);
      }
    });
  }, 100);
};

// 头像文件上传函数
const uploadAvatarFile = (userId, formData, onProgress) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    
    // 上传进度监听
    xhr.upload.addEventListener('progress', (e) => {
      if (e.lengthComputable) {
        const progress = Math.round((e.loaded / e.total) * 100);
        if (onProgress) onProgress(progress);
      }
    });
    
    // 请求完成监听
    xhr.addEventListener('load', () => {
      if (xhr.status === 200) {
        try {
          const response = JSON.parse(xhr.responseText);
          resolve(response);
        } catch (error) {
          reject(new Error('服务器响应格式错误'));
        }
      } else {
        try {
          const errorResponse = JSON.parse(xhr.responseText);
          reject(new Error(errorResponse.error || '上传失败'));
        } catch (error) {
          reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText}`));
        }
      }
    });
    
    // 错误监听
    xhr.addEventListener('error', () => {
      reject(new Error('网络连接失败'));
    });
    
    // 超时监听
    xhr.addEventListener('timeout', () => {
      reject(new Error('上传超时'));
    });
    
    // 配置请求
    const url = `/api/users/${userId}/avatar`;
    // console.log('📡 发送请求到:', url);
    xhr.open('POST', url);
    xhr.timeout = 30000; // 30秒超时
    
    // 发送请求
    // console.log('📤 发送FormData:', formData);
    xhr.send(formData);
    
    // 添加请求开始日志
    // console.log('🚀 头像上传请求已发送');
  });
};

// 处理文件上传
const handleFileUpload = (file, uploadArea, previewArea, previewImage) => {
  if (!file.type.startsWith('image/')) {
    showConfirmDialog('文件格式错误', '请选择图片文件');
    return;
  }
  
  if (file.size > 5 * 1024 * 1024) {
    showConfirmDialog('文件过大', '请选择小于5MB的图片');
    return;
  }
  
  const reader = new FileReader();
  reader.onload = (e) => {
    previewImage.src = e.target.result;
    uploadArea.style.display = 'none';
    previewArea.style.display = 'block';
  };
  reader.readAsDataURL(file);
};